/**
 * 权限控制脚本
 *
 * @format
 */
import router from "@/router"
import store from "@/store"
import _ from "lodash"
import { isValidDate } from "@/utils/date"

const addRoutes = routes => {
	const handler = (parentName, routes) => {
		routes.forEach(({ path, name, component, redirect, meta, children }) => {
			if (_.isNil(parentName)) {
				router.addRoute({
					path,
					name,
					component: () => import("@/views/" + component),
					redirect,
					meta,
				})
			} else {
				router.addRoute(parentName, {
					path,
					name,
					component: () => import("@/views/" + component),
					redirect,
					meta,
				})
			}
			if (_.isArray(children)) handler(name, children)
		})
	}
	handler(null, routes)
}

/**
 * 路由分三种
 * 一种是系统性的路由
 * 一种是第三方可访问路由
 * 一种是登录可访问路由
 *
 * 是否登录不影响前两种路由的访问
 * 地址错误时
 */
router.beforeEach(async (to, from, next) => {
	// 3分钟内是否更新过路由
	const routesUpdateTime = 3 * 60 * 1000
	const isRoutesUpdated = isValidDate(store.getters.routesUpdateTime)
		? new Date().getTime() - store.getters.routesUpdateTime.getTime() < routesUpdateTime
		: false

	if (isRoutesUpdated) {
		// 路由已更新
		if (to.meta.loginRequired) {
			// 路由需要登录
			if (store.getters.token) {
				// 用户已登录，放行
				next()
			} else {
				// 用户未登录，转到登录页面
				store.commit("routes/SET_ROUTES", [])
				if (to.fullPath === "/login") {
					next()
				} else {
					next("/login?to=" + to.path)
				}
			}
		} else {
			// 路由不需要登录，放行
			next()
		}
	} else {
		// 路由未更新
		await store.dispatch("routes/updateRoutes").then(routes => {
			addRoutes(routes)
		})
		next({ ...to, replace: true })
	}
})

router.beforeResolve((to, from, next) => {
	next()
})

router.afterEach((to, from, next) => {})
